var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var swig = require('swig');
var mongoose = require('mongoose');
var fs = require('fs');
var log4js = require('log4js');

var config = require('config');

var redisClient = require('./utils/redis');
var main = require('./controllers/main');

var app = express();

/********** log setting **********/
var logDirectory = path.join(__dirname, 'log');
// ensure log directory exists
if (!fs.existsSync(logDirectory))
  fs.mkdirSync(logDirectory);
log4js.configure('./config/log4js.json');
app.use(log4js.connectLogger(log4js.getLogger('http'), { level: 'auto'}));


/******** swig view engine setup ********/
app.engine('html', swig.renderFile);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
// Swig will cache templates for you, close Express's caching 
app.set('view cache', false);


/* 请求解析 */
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use('/static', express.static(path.join(__dirname, 'dist')));

/******** 路由规则 ********/
app.use('/main', main);
/**************************/

// 连接数据库
/*
dbConfig = config.dbConfig;
mongoose.connect(dbConfig.url);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
  console.log('mongodb connected');
});
*/

// 连接缓存
/*
redisClient.on('connect', function(){
  console.log('redis connected');
});
*/

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers
// development error handler
// will print stacktrace
if (process.env.NODE_ENV === 'dev') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    console.log(err);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
